package com.supor.aiot.home.ui.device.config;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.View;

import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.views.CenterImageSpan;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseConfigActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.entity.ProductType;
import com.supor.aiot.common.helper.ActivityHelper;
import com.supor.aiot.home.R;
import com.supor.aiot.home.databinding.ActivityNetGuideBinding;

import androidx.core.content.res.ResourcesCompat;

import static com.supor.aiot.common.app.Constants.SETTING_GPS;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: 网络引导页：AP配网 <br>
 * 作者: lei <br>
 * 日期: 2020/12/1 <br>
 */
public class NetGuideActivity extends BaseConfigActivity<NoViewModel, ActivityNetGuideBinding> {
    // 所需的全部权限
    private RxPermissions rxPermissions;
    /**
     * 1-GPS close
     */
    private int wifiStatus = 0;
    private String confirmTips;
    private ProductType.ProductModel productModel;

    @Override
    protected int resourceId() {
        return R.layout.activity_net_guide;
    }

    @Override
    public void initView() {
        super.initView();
        bindingView.setViewM(this);
        bindingView.topView.setConfig2Text(getString(R.string.top_start_ap));
        bindingView.toolbar.setIvLeftOnClickListener(v -> finish());
        bindingView.toolbar.setTvLeftOnClickListener(v -> finish());
        rxPermissions = new RxPermissions(this);
        confirmTips = getResources().getString(R.string.bind_confirm_action) + " (%1$ds)";
        if (getIntent() != null && getIntent().getExtras() != null) {
            productModel = (ProductType.ProductModel) getIntent().getSerializableExtra(Constants.Key.PRODUCT_MODEL);
            if (productModel == null) {
                Logc.d(TAG, "iotDevice is null");
                finish();
                return;
            }
            Bundle bundle = getIntent().getExtras();
            String ssid = bundle.getString(Constants.Key.SSID);
            String bssid = bundle.getString(Constants.Key.BSSID);
            String pass = bundle.getString(Constants.Key.PASS);
            Logc.i("net ssid= " + ssid + ", bssid= " + bssid + ", pass= " + pass);
        } else {
            finish();
            return;
        }

        if (Constants.Type.TYPE_CHEF_MACHINE.equalsIgnoreCase(productModel.modelTypeId)) {
            bindingView.gifIv.setImageResource(R.drawable.gif_net_reset);
            // 2. 打开设备，选择菜单-网络，点击【网络连接】按钮；
            String tip = getString(R.string.bind_net_guide_step2);
            SpannableString ss2 = new SpannableString(tip);

            ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("网络连接") - 1, tip.indexOf("网络连接") + 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep2.setText(ss2);

            // 3.当设备屏幕显示【网络连接中…】,即可点击下方的【下一步】按钮。
            tip = getString(R.string.bind_net_guide_step3);
            SpannableString ss3 = new SpannableString(tip);
            ss3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("网络连接") - 1, tip.indexOf("网络连接") + 7, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ss3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("下一步") - 1, tip.indexOf("下一步") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep3.setText(ss3);
        } else if (Constants.Type.TYPE_OVEN.equalsIgnoreCase(productModel.modelTypeId)) {
            bindingView.gifIv.setImageResource(R.drawable.gif_net_reset_oven);
            // 2. 长按产品【开始/暂停】按钮3秒；
            String tip = getString(R.string.bind_net_guide_oven_step2);
            SpannableString ss2 = new SpannableString(tip);

            ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("开始") - 1, tip.indexOf("开始") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep2.setText(ss2);

            // 3. 待产品Wi-Fi指示灯“&#160;&#160;&#160;”闪烁后，松开按钮，即可点击下方的【下一步】按钮。
            tip = getString(R.string.bind_net_guide_oven_step3);
            SpannableString ss3 = new SpannableString(tip);
            //拿到所加图片的drawable对象
            Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_net_guide_oven, null);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            CenterImageSpan imageSpan = new CenterImageSpan(drawable);
            ss3.setSpan(imageSpan, tip.indexOf("指示灯") + 5, tip.indexOf("指示灯") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ss3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("下一步") - 1, tip.indexOf("下一步") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep3.setText(ss3);
        } else if (Constants.Type.TYPE_RICE_COOKER.equalsIgnoreCase(productModel.modelTypeId)) {
            bindingView.gifIv.setImageResource(R.drawable.net_reset_rc);
            // 2. 长按设备【智定义】按钮5秒进入AP配网状态，“ WIFI ”灯闪烁，即可点击【下一步】按钮。
            String tip = getString(R.string.bind_net_guide_rice_cooker_step2);
            SpannableString ss2 = new SpannableString(tip);

            Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_wifi, null);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            CenterImageSpan imageSpan = new CenterImageSpan(drawable);

            ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("智定义") - 1, tip.indexOf("智定义") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("下一步") - 1, tip.indexOf("下一步") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            ss2.setSpan(imageSpan, tip.indexOf("WIFI"), tip.indexOf("WIFI") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep2.setText(ss2);
            bindingView.tvStep3.setVisibility(View.GONE);
        } else if (Constants.Type.TYPE_WATER_PURIFIER_UR2T1.equalsIgnoreCase(productModel.modelId)) {
            bindingView.gifIv.setImageResource(R.drawable.net_reset_ur2t1);
            // 2. 在机器进入正常工作状态后，长按【冲洗】键3秒；
            String tip = getString(R.string.bind_net_guide_water_purifier_ur2t1_step2);
            SpannableString ss2 = new SpannableString(tip);

            ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("冲洗") - 1, tip.indexOf("冲洗") + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep2.setText(ss2);

            // 3. 待 WIFI 指示灯闪烁，松开按钮，即可点击下方的【下一步】按钮；
            tip = getString(R.string.bind_net_guide_water_purifier_ur2t1_step3);
            SpannableString ss3 = new SpannableString(tip);

            Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.mipmap.ic_wifi, null);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            CenterImageSpan imageSpan = new CenterImageSpan(drawable);

            ss3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("下一步") - 1, tip.indexOf("下一步") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            ss3.setSpan(imageSpan, tip.indexOf("WIFI"), tip.indexOf("WIFI") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep3.setText(ss3);
        } else if (Constants.Type.TYPE_WATER_PURIFIER_UR106.equalsIgnoreCase(productModel.modelId)) {
            bindingView.gifIv.setImageResource(R.drawable.net_reset_ur106);
            // 2. 在机器进入正常工作状态后，1秒内双击【复位】键；
            String tip = getString(R.string.bind_net_guide_water_purifier_ur106_step2);
            SpannableString ss2 = new SpannableString(tip);

            ss2.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("复位") - 1, tip.indexOf("复位") + 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            bindingView.tvStep2.setText(ss2);

            // 3. 待蜂鸣器鸣叫1秒后，WIFI指示灯闪烁，即可点击下方的【下一步】按钮。
            tip = getString(R.string.bind_net_guide_water_purifier_ur106_step3);
            SpannableString ss3 = new SpannableString(tip);

            ss3.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                    tip.indexOf("下一步") - 1, tip.indexOf("下一步") + 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

            bindingView.tvStep3.setText(ss3);
        }

        bindingView.tvSlideTip.setOnClickListener(v ->
                bindingView.slideBtn.setOpen(!bindingView.slideBtn.isOpen()));
        bindingView.llConfirmAction.setOnClickListener(v ->
                bindingView.slideBtn.setOpen(!bindingView.slideBtn.isOpen()));
        bindingView.slideBtn.setOnSlideButtonChangeListener((view, isOpen) -> {
            bindingView.llConfirmAction.setSelected(isOpen);
            bindingView.tvSlideTip.setSelected(isOpen);
            bindingView.btnNextStep.setEnabled(isOpen);
        });

        checkLocationPermission();
    }

    /**
     * 检查定位权限
     */
    @SuppressLint({"CheckResult", "AutoDispose"})
    private void checkLocationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            rxPermissions.request(Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            //表示用户同意权限
                            checkWiFiStatus();
                        } else {
                            //表示用户不同意权限
                            Logc.i("request location failed");
                            tips(getResources().getString(R.string.bind_loc_permission_faild));
                        }
                    });
        } else {
            checkWiFiStatus();
        }
    }

    /**
     * 检查WiFi状态，步骤如下：
     * 1.检查GPS是否打开：未打开则弹框提示用户打开，取消-底部按钮置为设置，点击跳转GPS页面，
     *      确认-跳转GPS页面，若未打开返回则继续弹框
     */
    private void checkWiFiStatus() {
        if (!SystemUtils.isGpsEnabled(this)) {
            wifiStatus = 1;
            bindingView.btnNextStep.setText(R.string.setting);
            showDialog(getResources().getString(R.string.bind_wifi_turn_on_gps_title),
                    getResources().getString(R.string.bind_wifi_turn_on_gps_msg),
                    getResources().getString(R.string.setting),
                    (dialog, which) -> {
                        ActivityHelper.gotoGpsSetting(NetGuideActivity.this, SETTING_GPS);
                        dialog.dismiss();
                    },
                    getResources().getString(R.string.cancel),
                    (dialog, which) -> {
                        dialog.dismiss();
                    });
        } else {
            wifiStatus = 0;
            bindingView.btnNextStep.setText(R.string.next_step);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (SETTING_GPS == requestCode) {
            if (!SystemUtils.isGpsEnabled(this)) {
                tips(getResources().getString(R.string.bind_open_loc_faild));
                wifiStatus = 1;
                bindingView.btnNextStep.setEnabled(true);
                bindingView.btnNextStep.setText(R.string.setting);
            } else {
                wifiStatus = 0;
                checkWiFiStatus();
            }
        } else if (Constants.REQUEST_CODE == requestCode) {
            if (resultCode == 1) {
                setResult(1);
                finish();
            }
        }
    }

    private void gotoConfigActivity() {
        if (wifiStatus == 1) {
            ActivityHelper.gotoGpsSetting(NetGuideActivity.this, SETTING_GPS);
        } else {
            Intent intent = new Intent(NetGuideActivity.this, SelectWifiActivity.class);
            if (getIntent() != null && getIntent().getExtras() != null) {
                intent.putExtras(getIntent().getExtras());
            }
            intent.putExtra(Constants.Key.PRODUCT_MODEL, productModel);
            startActivityForResult(intent, Constants.REQUEST_CODE);
            // SuporPresenter.getInstance().reportGetTinyInfo();
            // TODO: 2021/8/13  
        }
    }

    public void onViewClicked(View view) {
        if (view.getId() == R.id.btn_next_step) {
            gotoConfigActivity();
        } else if (view.getId() == R.id.btn_cancel) {
            finish();
        }
    }
}
